import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import {Row,Col,Card,Form,Input,Select,Icon,Button,Dropdown,Menu,InputNumber,DatePicker,Modal,message,Tree,TreeSelect,Badge,Divider,Upload,Radio,label,Table,Popconfirm ,TimePicker} from 'antd';
import StandardTable from '../../components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './Role.less';

/*基础管理-用户管理*/
const { MonthPicker, RangePicker } = DatePicker;
const FormItem = Form.Item;
const Option = Select.Option;
var school_select=[];/*学校*/
var schoolName=[];//学校名字
var permissions=[];//权限组
var headerimg="";
var imageUrl="";
const getValue = obj =>Object.keys(obj).map(key => obj[key]).join(',');
var bjlssz=[];
//默认状态
var state;
function teachernOnChange(e){
	schoolName=e.split(",");
}


function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}
class Avatar extends React.Component {
  state = {  loading: false };
  handleChange = (info) => {
    if (info.file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    }
    if(info.file.status === 'done') {
    	headerimg=info.file.response.obj.path;
    	imageUrl=info.file.response.obj.path;
      // Get this url from response in real world.
      getBase64(info.file.originFileObj, imageUrl => this.setState({
        imageUrl,
        loading: false,
      }));
    }
  }
  render() {
    const uploadButton = (
      <div>
        <Icon type={this.state.loading ? 'loading' : 'plus'} />
        <div className="ant-upload-text">Upload</div>
      </div>
    );
	  if(imageUrl==undefined){
	  	 imageUrl = this.state.imageUrl;
	  }else{
	  	headerimg=imageUrl;
	  }
    const urls="api/web/attachment/upload.manage?token="+sessionStorage.getItem('token');
    return (
      <Upload
        name="file"
        style={{width:'100px'}}
        listType="picture-card"
        className="avatar-uploader"
        showUploadList={false}
        action={urls}
        method="POST"
        enctype="multipart/form-data"
        onChange={this.handleChange}
      >
        {imageUrl ? <img src={imageUrl} alt=""  style={{width:'100px'}} /> : uploadButton}
      </Upload>
    );
  }
}


const CreateForm = Form.create()(props => {
  const { modalVisible, form, handleAdd, handleModalVisible,title,obj} = props;
  const {getFieldDecorator} = form;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      	if(fieldsValue.name == undefined) {	fieldsValue.name = ""}
				if(fieldsValue.phone == undefined) {	fieldsValue.phone = ""}
				if(fieldsValue.loginAccount == undefined) {	fieldsValue.loginAccount = ""}
				if(fieldsValue.email == undefined) {	fieldsValue.email = ""}
				if(fieldsValue.state == undefined) {	fieldsValue.state = 1}
				fieldsValue.headPortrait=headerimg;
				fieldsValue.inJobDate=moment(fieldsValue.inJobDate).format('YYYY/MM/DD');
				fieldsValue.outJobDate=moment(fieldsValue.outJobDate).format('YYYY/MM/DD');
	      form.resetFields();
	      handleAdd(title,obj.employeeId,fieldsValue);
    });
  };
  return (
    <Modal
      maskClosable={false}
      destroyOnClose={true}
      width={'60%'}
      title={title}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible(false,'','')}
    >
    <Form layout = "horizontal" >
      	<FormItem label = "权限组"	labelCol = {{span: 4}}	wrapperCol = {{span: 18}} >
			{getFieldDecorator('roleId', {
				initialValue: obj.roleName,
				rules: [{required: true,message: '机构不能为空!'}],
			})(<Select allowClear placeholder="请选择权限">
					{permissions}
				</Select>)}
		    </FormItem>
		    <FormItem label="员工名称"   labelCol={{span: 8}}  wrapperCol={{span: 12}} className={styles.w50left}>
            {getFieldDecorator('name', {
            	 initialValue:obj.name,
              rules: [{ required: true, message: '员工名称不能为空!' }],
            })(<Input />)}
		    </FormItem>
	      <FormItem label="登录账号"   labelCol={{span: 8}}  wrapperCol={{span: 12}} className={styles.w50left}>
	        {getFieldDecorator('loginAccount',{
	        	 initialValue:obj.loginAccount,
	        	 rules: [{ required: true, message: '登录账号不能为空!' }],
	        })(<Input />)}
	      </FormItem>
      	<FormItem label="联系电话"  labelCol={{span: 8}}  wrapperCol={{span: 12}} className={styles.w50left}>
	        {getFieldDecorator('phone',{
	        	 initialValue:obj.phone,
	        	 rules: [{ required: true, message: '联系电话不能为空!' }],
	        })(<Input />)}
      	</FormItem>
	      <FormItem label="邮箱"  labelCol={{span: 8}}  wrapperCol={{span: 12}} className={styles.w50left}>
	        {getFieldDecorator('email',{
	        	 initialValue:obj.email,
	        	 rules: [{ required: true, message: '邮箱不能为空!' },
	        	 {type: 'email', message: '邮箱格式不正确!',},],
	        })(<Input />)}
	      </FormItem>
      	<FormItem label="职位描述"  labelCol={{span: 4}}  wrapperCol={{span: 18}}>
	        {getFieldDecorator('jobDescription',{
	        	initialValue:obj.jobDescription,
	        	rules: [{ required: true, message: '职位描述不能为空!' }],
	        })(<Input />)}
      	</FormItem>
		    <FormItem label="头像"  labelCol={{span: 4}}  wrapperCol={{span: 18}}>
		        {(<Avatar/>)}
		    </FormItem>
		    <FormItem label="入职时间"  labelCol={{span: 4}}  wrapperCol={{span: 17}}>
            {getFieldDecorator('inJobDate',{
            	 initialValue:obj.inJobDate ,
            })(<DatePicker/>)}
		    </FormItem>
		    <FormItem label="离职时间"  labelCol={{span: 4}}  wrapperCol={{span: 17}}>
            {getFieldDecorator('outJobDate',{
            	 initialValue:obj.outJobDate,
            })(<DatePicker />)}
		    </FormItem>
		    <FormItem label="状态"  labelCol={{span: 4}}  wrapperCol={{span: 18}}>
            {getFieldDecorator('state', {
            	 initialValue: obj.state==undefined ? "1":obj.state,
            	rules: [{ required: true, message: '状态不能为空!' }],
            })(<Select  placeholder="请选择状态"  >
              <Option value="1">有效</Option>
              <Option value="0">无效</Option>
            </Select>)}
		    </FormItem>

       	<FormItem label="学校"  labelCol={{span: 4}}  wrapperCol={{span: 18}}>
	        {getFieldDecorator('schoolId',{
	        	 initialValue:obj.schoolName,
	        	  rules: [{ required: true, message: '学校不能为空!' }],
	        })(<Select   searchPlaceholder="请选择" allowClear onChange={teachernOnChange}>
					{school_select}
				</Select> )}
      	</FormItem>

    	</Form>
    </Modal>
  );
});

@connect(({ manauser, loading,menu }) => ({
  manauser,
  loading: loading.models.manauser,
  threeMenu: menu.threeMenu,
}))
@Form.create()
export default class TableList extends PureComponent {
	state = {
	    modalVisible: false,
	    selectedRows: [],
	    formValues: {},
	    obj: "",
	};
  componentDidMount() {
  	/*按钮查询*/
		this.props.dispatch({type: 'menu/fetch_three_menu',});
  	/*默认查询table 数据*/
		this.props.dispatch({
			type: 'manauser/fetch_user',
			payload: {
				state :1,
			},
			});
	/*默认查询权限  tree*/
		this.props.dispatch({
			type: 'manauser/fetch_permissions',
			callback: (res,data) => {
				permissions=[];
				if(res==1){
					for (let i = 0; i < data.length; i++) {
						 permissions.push(<Option key={data[i].roleId}>{data[i].name}</Option>);
					}
				}
	    },
		});
		/*默认查询 学校 select */
		this.props.dispatch({
			type: 'manauser/fetch_ListByschoolselect',
			callback: (res,data) => {
				school_select=[];
				for (let i = 0; i < data.length; i++) {
				  school_select.push(<Option key={data[i].id+","+data[i].value}>{data[i].value}</Option>);
				}
			}
		});
  }

	handleStandardTableChange = (pagination, filtersArg, sorter) => {
	    const { dispatch } = this.props;
	    const { formValues } = this.state;
	    const filters = Object.keys(filtersArg).reduce((obj, key) => {
	    const newObj = { ...obj };
	      newObj[key] = getValue(filtersArg[key]);
	      return newObj;
	    }, {});
	    const params = {
	      currentPage: pagination.current,
	      pageSize: pagination.pageSize,
	      ...formValues,
	      ...filters,
	    };
	    if (sorter.field) {
	      params.sorter = `${sorter.field}_${sorter.order}`;
	    }
	    dispatch({
	      type: 'manauser/fetch_user',
	      payload: params,
	    });
	};
	handleSelectRows = rows => {
	    this.setState({
	      selectedRows: rows,
	    });
	};
	/*重置*/
	handleFormReset = () => {
		const {	form,	dispatch} = this.props;
		form.resetFields();
		this.setState({	formValues: {},});
		dispatch({type: 'manauser/fetch_user',});
	}
	/*查询*/
	handleSearch = e => {
	    e.preventDefault();
	    const { dispatch, form } = this.props;
	    form.validateFields((err, fieldsValue) => {
		    if (err) return;
		    const values = {  ...fieldsValue,};
		    this.setState({ formValues: values,});
		 	 	if(values.name == undefined) {	values.name = ""}
				if(values.phone == undefined) {	values.phone = ""}
				if(values.loginAccount == undefined) {	values.loginAccount = ""}
				if(values.email == undefined) {	values.email = ""}
				if(values.state == undefined) {	values.state = ""}
        dispatch({
	        type: 'manauser/fetch_user',
	        payload:{...values},
        });
	    });
	};
	/*弹窗*/
  handleModalVisible = (flag,record,title) => {
	  	if(flag==false){
	  		this.setState({
		      modalVisible: false,
		    });
	  	}else{
	  		var obj={};
	  		if(title=="新建"){
	  			 this.setState({
		      modalVisible: !!flag,
		      title: title,
		      obj: obj,
		    });
	  		}else{
		  		  const { selectedRows } = this.state;
			  		if(record==undefined||Object.keys(selectedRows).length==0){
				    	message.info("还未选择项");
				    }else if(Object.keys(selectedRows).length>1){
				    	message.info("只可选择一项");
				    }else{
				    	bjlssz = [selectedRows[0].schoolId,selectedRows[0].schoolName];
				  		selectedRows[0].inJobDate=moment(selectedRows[0].inJobDate);
						selectedRows[0].outJobDate=moment(selectedRows[0].outJobDate);
						selectedRows[0].state+='';
						selectedRows[0].orgId+='';
						selectedRows[0].roleId+='';
						if(selectedRows[0].headPortrait!=undefined){
							imageUrl=selectedRows[0].headPortrait;
						}
						obj=selectedRows[0];
					   	this.setState({
					      modalVisible: !!flag,
					      title: title,
					      obj: obj,
					    });
				  }
		  	}

	  	}
  	};
	/*新增,修改*/
	handleAdd = (title,Id,fields) => {
		if(title == "新建" || title == "编辑"){
			if(schoolName == null || schoolName == " " || schoolName.length == 0){
				console.log("进2");
				fields.schoolId = bjlssz[0];
				fields.schoolName = bjlssz[1];
			}else if(schoolName != undefined){
					fields.schoolId = schoolName[0];
					fields.schoolName = schoolName[1];
			}
		}
		if(title=="新建"){
		    this.props.dispatch({
		      type: 'manauser/add_user',
		      payload: {
		      	...fields,
		      	orgId :41,
		      },
		      callback: (res,resMsg) => {
		      	if(res==1){
		      		message.success(resMsg);
		      	}else{
		      		message.error(resMsg);
		      	}
		      },
		    });
	  	}else if(title=="编辑"){
	  		if(Id!=undefined){
	  			this.props.dispatch({
			      type: 'manauser/edit_user',
			      payload: {
			      	...fields,
			      	employeeId:Id,
			      },
			      callback: (res,resMsg) => {
			      	this.state.selectedRows=[];
			      	if(res==1){
			      		message.success(resMsg);
			      	}else{
			      		message.error(resMsg);
			      	}
			      },
			    });
	  		}else{
	  			message.info("还未选择项");
	  		}
	  	}
	    this.setState({
	      modalVisible: false,
	    });
	};

  /*删除*/
 	confirmModel=(title,Id)=>{
 		const { dispatch } = this.props;
		const { selectedRows } = this.state;
    if(Object.keys(selectedRows).length==0){
			message.info("还未选择项");
		}else{
    	var Ids=[];
	    Ids.push(selectedRows.map(row => row.employeeId).join(','));
	    if(title!="删除"){
	    	var state;
	    	if(title=="禁用"){
	    		state=0;
	    	}else{
	    		state=1;
	    	}
	    	Modal.confirm({
					title: '是否'+title+'选中项状态?',
					okText: '确定',
					cancelText: '取消',
					onOk() {
						/*批量修改状态*/
						dispatch({
							type: 'manauser/edit_user_state',
							payload: {
								employeeIds: Ids,
								state:state,
							},
							callback: (res, resMsg) => {
								if(res == 1) {
									message.success(resMsg);
								} else {
									message.error(resMsg);
								}
							},
						});
					}
				});
	    }else{
	    		Modal.confirm({
				    title: '是否删除当前数据选中',
				    content: '',
				    onOk() {
				      dispatch({
					      type: 'manauser/remove_user',
					      payload: {employeeIds:Ids,},
					      callback: (res,resMsg) => {
					      	if(res==1){
					      		message.success(resMsg);
					      	}else{
					      		message.error(resMsg);
					      	}
					      },
					  	});
				    },
				});
	    }
	  }
 	}
	renderSimpleForm() {
	    const { getFieldDecorator } = this.props.form;
	    return (
	      	<Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
           <Col md={8} sm={24}>
            <FormItem label="名称">
              {getFieldDecorator('name')(
                <Input placeholder="请输入" />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="电话">
              {getFieldDecorator('phone')(
                <Input placeholder="请输入" />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="登录账号">
              {getFieldDecorator('loginAccount')(
                <Input placeholder="请输入" />
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
         <Col md={8} sm={24}>
            <FormItem label="邮箱">
              {getFieldDecorator('email')(
                <Input placeholder="请输入" />
              )}
            </FormItem>
          </Col>
           <Col md={8} sm={24}>
            <FormItem label="状态">
              {getFieldDecorator('state')(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  <Option value="1">有效</Option>
                  <Option value="0">无效</Option>
                </Select>
              )}
            </FormItem>
          </Col>
           <Col md={8} sm={24}>
            <FormItem>
	            <span style={{ float: 'right', marginBottom: 24 }}>
	           		<Button type="primary" htmlType="submit">查询</Button>
	           		<Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>重置</Button>
	            </span>
            </FormItem>
          </Col>
        </Row>
      </Form>
	  );
	}
	render() {
	    const { manauser: { data },loading,threeMenu} = this.props;
	    const { selectedRows, modalVisible,title,obj } = this.state;
	    const columns = [ {
	    	title: '员工名称',
	    	dataIndex: 'name',
	    	key: 'name',
	    	width:'100px',
	    }, {
	    	title: '联系电话',
	    	dataIndex: 'phone',
	    	key: 'phone',
	    	width:'100px',
	    }, {
	    	title: '登陆账号',
	    	dataIndex: 'loginAccount',
	    	key: 'loginAccount',
	    	width:'100px',
	    }, {
	    	title: '邮箱',
	    	dataIndex: 'email',
	    	key: 'email',
	    	width:'100px',
	    }, {
	    	title: '状态',
	    	dataIndex: 'state',
	    	key: 'state',
	    	width:'100px',
	    	render: (text, record, index) => {
	    		if(record.state == 1) {
	    			return "有效"
	    		} else if(record.state == 0) {
	    			return "无效"
	    		}
	    	}
	    }];
	    const parentMethods = {
	      	handleAdd: this.handleAdd,
	      	handleModalVisible: this.handleModalVisible,
	      	confirmModel:this.confirmModel,
	    };
	    return (
	    	 <PageHeaderLayout title="员工系统/人员管理">
	      <Card bordered={false}>
	          <div className={styles.tableList}>
	            <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>
	            <span>
	            	{!threeMenu.new && <Button type="primary" onClick={() => this.handleModalVisible(true,'','新建')} style={{ marginLeft: 8 }}>新建</Button>}
	            	{!threeMenu.edit && <Button type="primary" onClick={() => this.handleModalVisible(true,'','编辑')} style={{ marginLeft: 8 }}>编辑</Button>}
	            	{/*<Button type="primary"  onClick={() => this.confirmModel('删除')}>删除</Button>*/}
	            	{!threeMenu.enable && <Button type="primary"  onClick={() => this.confirmModel('启用')}  style={{ marginLeft: 8 }}>启用</Button>}
					{!threeMenu.enable && <Button  type="ghost"  onClick={() => this.confirmModel('禁用')}  style={{ marginLeft: 8 }}>禁用</Button>}
	            </span>
	            <StandardTable
	              selectedRows={selectedRows}
	              loading={loading}
	              data={data}
	              columns={columns}
	              onSelectRow={this.handleSelectRows}
	              onChange={this.handleStandardTableChange}
	            />
	          </div>
	        <CreateForm {...parentMethods} modalVisible={modalVisible} title={title} obj={obj}/>
	      </Card>
	      </PageHeaderLayout>
	    );
	}
}
